package com.annoncesautomobile.vue;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.annoncesautomobile.R;
import com.annoncesautomobile.modele.concreteEntities.PubAutoPromo;
import com.annoncesautomobile.modele.util.ModelXML;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class SplashActivity extends Activity {

	private static int SPLASH_TIME_OUT = 800;

	private ImageView imageView;
	private ModelXML modele;

	private PubAutoPromo pub = null;
	private Drawable d = null;

	private Object lock = new Object();
	private boolean timer = false;
	private boolean draw = false;

	private static final String PREFERENCES_NAME = "ANNONCE_AUTO";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	private static final String TAG = "GCM Demo";

	/**
	 * Substitute you own sender ID here. This is the project number you got
	 * from the API Console, as described in "Getting Started."
	 */
	//private String SENDER_ID = "19945176581";
	private String SENDER_ID = "307293029260";

	private GoogleCloudMessaging gcm;
	//private AtomicInteger msgId = new AtomicInteger();
	private Context context = this;
	private String regid;

	private boolean isFromNotif = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		modele = ModelXML.getInstance();

		this.imageView = (ImageView) findViewById(R.id.imgPub);
		this.imageView.setImageResource(R.drawable.launch_image);

		isFromNotif = getIntent().getBooleanExtra("fromNotif", false);
		System.out.println("ISFROMNOTIF SPLASH: " + isFromNotif);
		context = getApplicationContext();

		// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
		if(isOnline())
		{
			if (checkPlayServices()) {
				gcm = GoogleCloudMessaging.getInstance(this);
				regid = getRegistrationId(context);

				if (regid.length() == 0) {
					registerInBackground();
				}
				else
				{
					new getPub().execute();
				}
			} else {
				Log.i(TAG, "No valid Google Play Services APK found.");
			}


			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					setFlagOrStart(0);
				}
			}, SPLASH_TIME_OUT);
		}
		else
		{
			final Dialog dialog = new Dialog(SplashActivity.this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.modal_ok);
			final TextView text = (TextView) dialog.findViewById(R.id.text);
			text.setText("Une connexion Internet est requise pour cette application.");

			Button buttonNogo = (Button) dialog.findViewById(R.id.buttonOk);
			buttonNogo.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					android.os.Process.killProcess(android.os.Process.myPid());
					System.exit(0);
				}
			});

			dialog.show();        	
		}
	}

	public boolean isInternetAvailable = true;

	public boolean isOnline() {
		try
		{
			ConnectivityManager cm =
					(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnectedOrConnecting()){
				try
				{
					return new AsyncTask<Void, Void, Boolean>() {

						@Override
						protected Boolean doInBackground(Void... arg0) {
							try
							{
								return modele.testInternetConnexion();
							}
							catch(RuntimeException e)
							{
								return false;
							}
						}
					}.execute().get();
				}
				catch(Exception e)
				{
					Log.e("Error : " ,"Chatch2",e);
					return false;
				}
			}
		}
		catch(Exception e)
		{
			Log.e("Error : " ,"Catch 1" , e);
			return false;
		}
		return false;
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If
	 * it doesn't, display a dialog that allows users to download the APK from
	 * the Google Play Store or enable it in the device's system settings.
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(TAG, "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	/**
	 * Gets the current registration ID for application on GCM service, if there is one.
	 * <p>
	 * If result is empty, the app needs to register.
	 *
	 * @return registration ID, or empty string if there is no existing
	 *         registration ID.
	 */
	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getGcmPreferences(context);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.length() == 0) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		System.out.println("registrationId : "+registrationId);
		return registrationId;
	}

	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and the app versionCode in the application's
	 * shared preferences.
	 */
	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regid = gcm.register(SENDER_ID);
					System.out.println("regid : "+regid);
					msg = "Device registered, registration ID=" + regid;

					// You should send the registration ID to your server over HTTP, so it
					// can use GCM/HTTP or CCS to send messages to your app.
					//sendRegistrationIdToBackend();

					// For this demo: we don't need to send it because the device will send
					// upstream messages to a server that echo back the message using the
					// 'from' address in the message.

					// Persist the regID - no need to register again.
					storeRegistrationId(context, regid);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					// If there is an error, don't just keep trying to register.
					// Require the user to click a button again, or perform
					// exponential back-off.
				}
				System.out.println("msg : "+msg);
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				//mDisplay.append(msg + "\n");
				new getPub().execute();
			}
		}.execute(null, null, null);
	}

	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGcmPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences, but
		// how you store the regID in your app is up to you.
		return getSharedPreferences(SplashActivity.PREFERENCES_NAME, Context.MODE_PRIVATE);
	}

	/**
	 * Stores the registration ID and the app versionCode in the application's
	 * {@code SharedPreferences}.
	 *
	 * @param context application's context.
	 * @param regId registration ID
	 */
	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getGcmPreferences(context);
		int appVersion = getAppVersion(context);
		Log.i(TAG, "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}


	private class getPub extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... args) {
			modele.getPubAutoPromo();
			return null;
		}

		@Override
		protected void onPostExecute(Integer i)
		{
			pub = modele.getPubAutoPromo();
			lancerDL();
		}
	}

	protected void lancerDL()
	{
		new getImage().execute();
	}



	private class getImage extends AsyncTask<Void, Void, Drawable> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Drawable doInBackground(Void... args) 
		{
			InputStream is = null;
			HttpGet httpGet = new HttpGet(pub.getLienImage320x568());
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response;
			try {
				response = httpClient.execute(httpGet);
				is = response.getEntity().getContent();
				return Drawable.createFromStream(is, null);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}	
			return null;
		}

		@Override
		protected void onPostExecute(Drawable dtmp)
		{
			d = dtmp;
			setFlagOrStart(1);
		}
	}


	protected void setFlagOrStart(int what)
	{
		synchronized (lock) {
			if(what == 0)
			{
				timer = true;
			}
			else
			{
				draw = true;
			}
			if(timer && draw)
			{
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
				byte[] bitmapdata = stream.toByteArray();
				String fileName = "publicite"+".jpg";
				try {
					FileOutputStream fileOutStream = openFileOutput(fileName, MODE_PRIVATE);
					fileOutStream.write(bitmapdata);  //b is byte array 
					fileOutStream.close();
					Intent intent = new Intent(this, SplashScreenAffichagePub.class);
					intent.putExtra("picname", fileName);
					intent.putExtra("fromNotif", isFromNotif);
					startActivity(intent);
					overridePendingTransition(R.anim.grow_from_middle,R.anim.shrink_to_middle);
					finish();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


}
